package main

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

func getToken() string {
	var host = "https://aip.baidubce.com/oauth/2.0/token"
	var param = map[string]string{
		"grant_type":    "client_credentials",
		"client_id":     "kGvVPYnrpHcm1WAEWtrGWVxP",
		"client_secret": "qpiVf4Azqt9YjGi18LO8HqCcWa6ADhZN",
	}

	uri, err := url.Parse(host)
	if err != nil {
		fmt.Println(err)
	}
	query := uri.Query()
	for k, v := range param {
		query.Set(k, v)
	}
	uri.RawQuery = query.Encode()

	response, err := http.Get(uri.String())
	if err != nil {
		fmt.Println(err)
	}
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println(err)
	}
	// fmt.Println(string(result))
	var v interface{}
	json.Unmarshal([]byte(string(result)), &v)
	resultmes := v.(map[string]interface{})

	mes := resultmes["access_token"].(string)

	return mes
}

func setface() {
	accessToken := getToken()
	var host = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add"

	uri, err := url.Parse(host)
	if err != nil {
		fmt.Println(err)
	}
	query := uri.Query()
	query.Set("access_token", accessToken)
	uri.RawQuery = query.Encode()
	filebytes, err := ioutil.ReadFile("z.jpg")
	if err != nil {
		fmt.Println(err)
	}
	image := base64.StdEncoding.EncodeToString(filebytes)
	var params = map[string]string{}
	params["image"] = image
	params["image_type"] = "BASE64"
	params["group_id"] = "girl"
	params["user_id"] = "whh"
	sendBody, err := json.Marshal(params)
	if err != nil {
		fmt.Println(err)
	}
	sendData := string(sendBody)
	client := &http.Client{}
	request, err := http.NewRequest("POST", uri.String(), strings.NewReader(sendData))
	if err != nil {
		fmt.Println(err)
	}
	request.Header.Set("Content-Type", "application/json")
	response, err := client.Do(request)
	defer response.Body.Close()
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(result))
}

func test() {
	var host = "https://aip.baidubce.com/rest/2.0/face/v3/faceverify"
	accessToken := getToken()
	uri, err := url.Parse(host)
	if err != nil {
		fmt.Println(err)
	}
	query := uri.Query()
	query.Set("access_token", accessToken)
	uri.RawQuery = query.Encode()
	filebytes, err := ioutil.ReadFile("z.jpg")
	if err != nil {
		fmt.Println(err)
	}
	image := base64.StdEncoding.EncodeToString(filebytes)
	var params = map[string]string{}
	params["image"] = image
	params["image_type"] = "BASE64"
	sendBody, err := json.Marshal(params)
	if err != nil {
		fmt.Println(err)
	}
	sendData := string(sendBody)
	client := &http.Client{}
	request, err := http.NewRequest("POST", uri.String(), strings.NewReader(sendData))
	if err != nil {
		fmt.Println(err)
	}
	request.Header.Set("Content-Type", "application/json")
	response, err := client.Do(request)
	defer response.Body.Close()
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(result))
}

func main() {
	test()

}
